package com.zhangtai.mq.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.rabbitmq.client.Channel;
import com.zhangtai.Neusoft.constVo.EmployeeChangeConst;
import com.zhangtai.exception.RException;
import com.zhangtai.exception.SendErr;
import com.zhangtai.utils.DateUtils;
import com.zhangtai.utils.NeuAES;
import com.zhangtai.utils.R;
import com.zhangtai.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

@Component
@Slf4j
public class EmployeeChangeListener {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${neu.applyUrl}")
    private String neuUrl;

    @Autowired
    private SendErr sendErr;


//    @RabbitListener(queues = "EMPLOYEE_CHANGE_QUEUE") //测试队列队列
    public void rabbitMqListener(Channel channel, Message message){
        String s = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("监听的消息是:{}", s);
//        如果消息为空，则签收
        if (StringUtils.isEmpty(s)){
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                e.printStackTrace();

            }
        }

        try {
            JSONObject jsonObject = JSON.parseObject(s);
            String type = jsonObject.getString("type");  //获取类型
            String path = "";
            if(EmployeeChangeConst.CHANGE_TYPE_NEW.equals(type)){
                path = "/transfer/newEntryInfo";
            }else if(EmployeeChangeConst.CHANGE_TYPE_REGULAR.equals(type)){
                path = "/transfer/positiveApply";
            }else if(EmployeeChangeConst.CHANGE_TYPE_TRANSFER.equals(type)){
                path = "/transfer/newTranApplyInfo";
            }else if(EmployeeChangeConst.CHANGE_TYPE_DIMISSION.equals(type)){
                path = "/transfer/newOutApplyInfo";
            }else if(EmployeeChangeConst.CHANGE_TYPE_CONTRACT.equals(type)){
                path = "/transfer/newContract";
            }else if(EmployeeChangeConst.SECURITY_TYPE_SECURITY.equals(type)){
                path = "/salary/saveShebao";
            }else if(EmployeeChangeConst.SECURITY_TYPE_FUNDS.equals(type)){
                path = "/salary/saveAcfun";
            }else if(EmployeeChangeConst.SECURITY_TYPE_CREDENTIAL.equals(type)){
                path = "salary/saveGuazbt";
            }
            send(jsonObject,path);

        } catch (Exception e) {
            log.error("mq消费者报错\n"+ Arrays.asList(e.getStackTrace()));
            log.error("请求报文是：{}",s);
            String time = DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN);
            ArrayList<StackTraceElement> stackTraceElements = new ArrayList<>();
            for (StackTraceElement stackTraceElement : e.getStackTrace()) {
                if (stackTraceElement.toString().contains("com.zhangtai")){
                    stackTraceElements.add(stackTraceElement);
                }
            }
            sendErr.sendMsg(time+",mq消费者报错:"+e+"\n"+ stackTraceElements);
            throw new RException("mq消费者报错",e);
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private R send(JSONObject jsonObject,String path){
        String token = NeuAES.getToken();
        String url=neuUrl+path;
        jsonObject.put("clientToken",token);
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(jsonObject, httpHeaders);
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        log.info("ehr接口地址{}，请求参数{}",path,jsonObject.toJSONString());
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
        JSONObject body = responseEntity.getBody();
        log.info("ehr接口地址{}，返回结果{}",path,body.toJSONString());
        if (ObjectUtils.isEmpty(body)){
            return R.error();
        }
        Boolean success = body.getBoolean("success");
        if (!success||ObjectUtils.isEmpty(success)){
            return R.error();
        }
        String message = body.getString("message");
        if (StringUtils.isEmpty(message)){
            return R.error();
        }
        return R.ok();
    }
}
